package cn.tianjindong.blog_portal.service.impl;

import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.tianjindong.blog.common.utils.MailUtils;
import cn.tianjindong.blog.common.utils.RandomUtils;
import cn.tianjindong.blog.mapper.BlogUserCollectionMapper;
import cn.tianjindong.blog.mapper.BlogUserMapper;
import cn.tianjindong.blog.mapper.BlogVisitlogMapper;
import cn.tianjindong.blog.pojo.BlogUser;
import cn.tianjindong.blog.pojo.BlogUserCollection;
import cn.tianjindong.blog.pojo.BlogUserCollectionExample;
import cn.tianjindong.blog.pojo.BlogUserExample;
import cn.tianjindong.blog.pojo.BlogUserExample.Criteria;
import cn.tianjindong.blog.pojo.BlogVisitlog;
import cn.tianjindong.blog_portal.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private BlogUserMapper userMapper;

	@Autowired
	private BlogUserCollectionMapper userCollectionMapper;
	
	@Autowired
	private BlogVisitlogMapper visitMapper;

	@Autowired
	private MailUtils mailUtils;// 邮件操作工具类

	@Value("${website.domain}")
	private String domainName;// 网站的域名（在website.properties中配置）

	@Override
	public BlogUser selectByUsernameOrEmail(String username) {
		BlogUser user = userMapper.selectByUsernameOrEmail(username);
		return user;
	}

	public boolean checkUsername(String username) {
		BlogUserExample example = new BlogUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<BlogUser> selectByExample = userMapper.selectByExample(example);
		if (selectByExample != null && selectByExample.size() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean checkEmail(String email) {
		BlogUserExample example = new BlogUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andEmailEqualTo(email);
		List<BlogUser> selectByExample = userMapper.selectByExample(example);
		if (selectByExample != null && selectByExample.size() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public void createAccount(BlogUser user) {
		user.setName(user.getUsername());// 设置初始昵称与用户名相同
		Date date = new Date();
		user.setCreatetime(date);
		String activationCode = RandomUtils.getRandomCode(6, 3);
		user.setName(user.getUsername());//默认情况下昵称和用户名相同
		user.setActivationCode(activationCode);// 设置激活校验码
		user.setActivation(0);// 设置激活标志位：0表示未激活，1表示激活
		userMapper.insertReturnID(user);

		// 激活链接格式：http://www.tianjindong.cn/account/activation/{user_id}/{activationCode}.action;
		StringBuffer activateUrl = new StringBuffer("http://" + domainName + "/account/activation/");
		activateUrl.append(user.getId() + "/");
		activateUrl.append(activationCode + ".action");

		// 生成邮件内容
		StringBuffer content = new StringBuffer(
				"<html><head></head><body><center style='background: #F8F8F8'><table cellpadding='8' cellspacing='0' border='0'><tbody><tr><td valign='top'><table cellpadding='0' cellspacing='0' border='0' align='center'><tbody><tr><td colspan='3' height='42'></td></tr><tr><td colspan='2' style='font-size: 0px;' align='left' height='1'><img src='http://47.101.188.10:8888/group1/M00/00/00/rBAiPVyCL32AJuOTAABG_b00rqs824.png' style='max-height: 100px; width:200px;' /></td></tr><tr><td colspan='3' height='24'></td></tr><tr><td colspan='3'><table cellpadding='0' cellspacing='0' style='line-height: 25px; background: #fff;-moz-box-shadow:0px 0px 5px #E6E6E6; -webkit-box-shadow:0px 0px 5px #E6E6E6; box-shadow:0px 0px 5px #E6E6E6;-moz-border-radius:3px; -webkit-border-radius:3px; border-radius:3px;' border='0' align='center'><tbody><tr><td colspan='3' height='30'></td></tr><tr><td width='40'></td><td width='600' style='border-bottom:1px solid #DDDDDD; max-width:600px'><h1 style='color: #3C414B; font-weight:400; font-size:22px; margin-bottom: 30px'> 账号激活</h1></td><td width='40'></td></tr><tr><td colspan='3' height='40'></td></tr><tr><td width='40'></td><td width='600' align='left' style='color:#3C414B; border-collapse: collapse; font-size: 16px;max-width: 600px;' valign='top'><span>感谢您使用听到微笑的博客，您已经注册了名为<strong>");
		content.append(user.getEmail());
		content.append("</strong>的账户，您需要点击下方的链接激活该账户。<br /><br /> 激活链接：<a href='");
		content.append(activateUrl);
		content.append("'>");
		content.append(activateUrl);
		content.append(
				"</a><br /><br /> 如果你并未发起请求可忽略此邮件，无需采取任何操作。</span></td><td width='40'></td></tr><tr><td colspan='3' height='30'></td></tr></tbody></table></td></tr></tbody></table><table cellpadding='0' cellspacing='0' align='center' border='0'><tbody><tr><td height='10'></td></tr><tr><td style='padding: 0; border-collapse: collapse;'><table cellpadding='0' cellspacing='0' align='center' border='0'><tbody><tr><td height='8'></td></tr><tr style='color: #C2C4C6; font-size: 14px;-webkit-text-size-adjust: none;'><td width='128' align='center' height='64' style='color:#C2C4C6'>www.tianjindong.cn</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></center></body></html>");

		try {
			mailUtils.sendMail(user.getEmail(), "账户激活", content.toString());
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void updateUserInfo(BlogUser user) {
		// 清除其余不可更改的字段
		user.setUsername(null);
		user.setActivation(null);
		user.setCreatetime(null);
		user.setActivationCode(null);
		user.setActivetime(null);
		user.setEmail(null);
		// 判断头像URL是否改变,如果没改变则设为null
		if (user.getImgurl() == null || user.getImgurl().equals("")) {
			user.setImgurl(null);
		}
		userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public BlogUser getUserById(Long id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public void collectArticle(Long userId, Long articleId) {
		BlogUserCollection collection = new BlogUserCollection();
		collection.setUserId(userId);
		collection.setArticleId(articleId);
		collection.setLinkTime(new Date());
		userCollectionMapper.insert(collection);
	}

	@Override
	public void unCollectArticle(Long id, Long articleId) {
		BlogUserCollectionExample example = new BlogUserCollectionExample();
		cn.tianjindong.blog.pojo.BlogUserCollectionExample.Criteria criteria = example.createCriteria();
		criteria.andArticleIdEqualTo(articleId);
		criteria.andUserIdEqualTo(id);
		userCollectionMapper.deleteByExample(example);
	}

	@Override
	public boolean checkArticleIsCollection(Long userId, Long articleId) {
		BlogUserCollectionExample example = new BlogUserCollectionExample();
		cn.tianjindong.blog.pojo.BlogUserCollectionExample.Criteria criteria = example.createCriteria();
		criteria.andArticleIdEqualTo(articleId);
		criteria.andUserIdEqualTo(userId);
		int count = userCollectionMapper.countByExample(example);
		return count > 0;
	}

	@Override
	public int activateAccount(Long userId, String activationCode) {
		BlogUser user = userMapper.selectByPrimaryKey(userId);
		Integer status=null;
		if (user == null) {
			return -2;// 数据库中没有该用户
		} else {
			if(user.getActivation()==0){//处于未激活状态
				if (activationCode.equals(user.getActivationCode())) {//只有处于未激活状态，并且激活码正确才进行激活
					BlogUser blogUser = new BlogUser();
					blogUser.setId(userId);
					blogUser.setActivetime(new Date());
					blogUser.setActivation(1);// 0表示未激活，1表示激活，-1表示作废
					userMapper.updateByPrimaryKeySelective(blogUser);
					return 0;//更新前为“未激活状态”
				} else {
					return -3;//激活码错误
				}
				
			}
			return user.getActivation();//可能为-1,1
		}
	}

	@Override
	public void addVisitLog(Long userId,String ip) {
		BlogVisitlog log = new BlogVisitlog();
		log.setIpaddress(ip);
		log.setUserId(userId);
		log.setVisitTime(new Date());
		visitMapper.insert(log);
	}
}
